<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item :label="t('batch.fields.batchName')" prop="batchName">
        <el-input
          v-model="queryParams.batchName"
          :placeholder="t('common.inputTextPlaceholder') + t('batch.fields.batchName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        />
      </el-form-item>
      <el-form-item :label="t('batch.fields.year')" prop="year">
        <el-input
          v-model="queryParams.year"
          :placeholder="t('common.inputTextPlaceholder') + t('batch.fields.year')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" :disabled="advancedSearching">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery" :disabled="advancedSearching">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['recruit:batch:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.add') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="toolbarRef" custom />
    <vxe-table
      id="iBatch-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('batch.fields.batchName')"
        field="batchName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('batch.fields.year')"
        field="year"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('batch.fields.phase')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          {{ getStatus(scope.row) }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('batch.fields.recruitTime')"
        field="recruitStartTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <p>{{ vxeDateFormatter({ cellValue: scope.row.recruitStartTime }) }}</p>
          <p>{{ vxeDateFormatter({ cellValue: scope.row.recruitEndTime }) }}</p>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('batch.fields.remark')"
        field="remark"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('batch.fields.createTime')"
        field="createTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :formatter="vxeDateFormatter"
        :visible="false"
      />
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="250"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['recruit:batch:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleSetupStage(scope.row)"
            v-hasPermi="['recruit:batch:update']"
          >
            {{ t('batch.operate.setupStage') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleSetMentor(scope.row)"
            v-hasPermi="['recruit:batch:update']"
          >
            {{ t('batch.operate.setupMentor') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleImportMentor(scope.row)"
            v-hasPermi="['recruit:batch:update']"
          >
            {{ t('batch.operate.importMentor') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleSetupSpecialist(scope.row)"
            v-hasPermi="['recruit:batch:update']"
          >
            {{ t('batch.operate.setupSpecialist') }}
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BatchForm ref="formRef" @success="getList" />
  <ExcelImportForm
    ref="importFormRef"
    object-name="招生计划"
    upload-url="/recruit/batch/import"
    template-url="/recruit/batch/get-import-template"
    @success="getList"
  />

  <BatchStage ref="batchStageRef" />
  <BatchMentorSelect ref="batchMentorRef" />
  <BatchSpecialistSelect ref="batchSpecialistRef" />
  <!-- 导入招生导师 -->
  <BatchMentorImport ref="batchMentorImportRef" />
</template>

<script setup lang="ts">
import { vxeDateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { BatchApi, BatchVO } from '@/api/recruit/batch'
import BatchForm from './BatchForm.vue'
import ExcelImportForm from '@/components/ExcelImportForm/index.vue'
import type { VxeTableInstance, VxeTablePropTypes, VxeToolbarInstance } from 'vxe-table'
import { useAppStore } from '@/store/modules/app'
import BatchMentorSelect from '@/views/recruit/batchmentor/BatchMentorSelect.vue'
import BatchSpecialistSelect from '@/views/recruit/batchspecialist/BatchSpecialistSelect.vue'
import BatchMentorImport from '@/views/recruit/batchmentor/components/BatchMentorImport.vue'
import BatchStage from '@/views/recruit/batchstage/index.vue'

/** 招生计划 列表 */
defineOptions({ name: 'Batch' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()

const loading = ref(true) // 列表的加载中
const list = ref<BatchVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const advancedSearching = ref(false) // 高级搜索
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  advanced: undefined,
  batchName: undefined,
  year: undefined,
  recruitStartTime: [],
  recruitEndTime: [],
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const batchStageRef = ref<InstanceType<typeof BatchStage>>()
const batchMentorRef = ref<InstanceType<typeof BatchMentorSelect>>()
const batchSpecialistRef = ref<InstanceType<typeof BatchSpecialistSelect>>()
const batchMentorImportRef = ref<InstanceType<typeof BatchMentorImport>>()

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BatchApi.getBatchPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  advancedSearching.value = false
  ;(queryParams as any).advanced = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof BatchForm>>()
const openForm = (type: string, id?: string) => {
  formRef.value?.open(type, id)
}

/** 导入 */
const importFormRef = ref<InstanceType<typeof ExcelImportForm>>()
const handleImport = () => {
  importFormRef.value?.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BatchApi.deleteBatch(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BatchApi.exportBatch(queryParams)
    download.excel(data, '招生计划.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleAdvanceSearch = (base64Advanced?: string) => {
  ;(queryParams as any).advanced = base64Advanced
  advancedSearching.value = !!base64Advanced
  handleQuery()
}

const getStatus = (row: BatchVO) => {
  const now = new Date().getTime()
  const recruitStartTime = new Date(row.recruitStartTime).getTime()
  const recruitEndTime = new Date(row.recruitEndTime).getTime()
  if (now < recruitStartTime) {
    return t('batch.phase.phase1')
  } else if (now >= recruitStartTime && now <= recruitEndTime) {
    return t('batch.phase.phase2')
  } else if (now > recruitEndTime) {
    return t('batch.phase.phase3')
  }
}

// 设置报名阶段
const handleSetupStage = (row: BatchVO) => {
  batchStageRef.value?.open(row.id)
}

// 弹窗设置导师
const handleSetMentor = (row: BatchVO) => {
  batchMentorRef.value?.open(row.id)
}

// 导入导师
const handleImportMentor = (row: BatchVO) => {
  batchMentorImportRef.value?.open(row.id)
}

// 弹窗设置专家
const handleSetupSpecialist = (row: BatchVO) => {
  batchSpecialistRef.value?.open(row.id)
}

/** 初始化 **/
onMounted(() => {
  getList()

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})
</script>

<style lang="scss" scoped>
:deep(.vxe-cell .el-button + .el-button) {
  margin-left: 0;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 15px !important;
}
</style>
